﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using OutDbContext;
using Quartz;
using User.Api.Helpers;

namespace Out.TaskRunner.QuartzJobs
{
    public class SendNewPaperJob: IJob
    {
        //private static readonly ILog Logger = LogManager.GetLogger(typeof(TransferDeptAndDoctorInfoJob));

        public void Execute(IJobExecutionContext context)
        {
            //Logger.InfoFormat("Executing job: {0}", context.JobDetail.Key);

            using (var ctx = new FsssdqfybjyEntities())
            {
                var papers =
                    ctx.SIWaitInvestigatePapers.Where(
                        x =>
                            x.IsSended == 0 &&
                            SqlFunctions.DateDiff("SECOND", x.NeedSendTime, SqlFunctions.GetDate()) > 0).Take(20).ToList();
                var unsendPapers = papers.Where(x => x.Status == 0);
                foreach (var paper in papers)
                {
                    paper.IsSended = 1;
                    paper.SendTime = DateTime.Now;
                    //ctx.SaveChanges();
                }
                ctx.SaveChanges();

                foreach (var paper in unsendPapers)
                {
                    var hospCards =
                        ctx.HospCards.Where(x => x.CardNo == paper.CardNo && x.RecStatus == 1)
                            .Select(x => new {CardId = x.Id})
                            .ToList();
                    foreach (var hospCard in hospCards)
                    {
                        MessageHelper.SendNewPaperMsg(hospCard.CardId.ToInt32OrDefault());
                    }
                }
            }
        }
    }
}
